package org.iabako.server.controller.timer.business;

import org.apache.log4j.Logger;
import org.iabako.server.conf.AppConf;
import org.iabako.server.dao.business.TrackingDAO;
import org.iabako.server.dao.user.UserDAO;
import org.iabako.server.mail.IabakoMailHelper;
import org.iabako.server.mail.IabakoMailSender;
import org.iabako.server.mail.template.TrackingEmailTemplate;
import org.iabako.server.tools.BundleMessages;
import org.iabako.server.tools.ServerTools;
import org.iabako.shared.entity.business.Tracking;
import org.iabako.shared.entity.user.Enterprise;
import org.iabako.shared.entity.user.User;
import org.iabako.shared.tools.GenericTools;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by jose on 22/05/15.
 */

@Controller
public class SendTrackingRecapControllerTimer {

    static Logger log = Logger.getLogger(SendNotificationRecapControllerTimer.class.getName());

    @Autowired
    UserDAO userDAO;
    @Autowired
    TrackingDAO trackingDAO;
    @Autowired
    private AppConf appConf;
    @Autowired
    TrackingEmailTemplate trackingEmailTemplate;
    @Autowired
    IabakoMailSender iabakoMailSender;
    @Autowired
    BundleMessages messages;

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    //Every day at 01:30 AM
    @Scheduled(cron = "0 45 1 * * ?")
    //@Scheduled(initialDelay = 10000, fixedRate = 120000)
    public void action() throws Exception {
        log.info("Executing SendTrackingRecapControllerTimer...");

        Map<Enterprise, List<User>> multiUserEnterprises = userDAO.getMultiUsersEnterprises();
        log.info("Number of multi-user enterprises : " + multiUserEnterprises.size());

        for (Enterprise enterprise : multiUserEnterprises.keySet()) {

            ServerTools serverTools = new ServerTools();
            Date today = serverTools.resetTime(new Date());
            Date yesterday = serverTools.addDaysToDate(today, -1);

            List<Tracking> trackingList = trackingDAO.getTrackingByDateAndUsers(yesterday, multiUserEnterprises.get(enterprise));

            if (trackingList.isEmpty()) {
                //There is no activity detected for this multi-user enterprise
                continue;
            }

            for (User user : enterprise.getUsers()) {
                TrackingEmailTemplate template = trackingEmailTemplate.getInstance(enterprise, user, trackingList);
                if (template == null) {
                    //There is no body in the email for this user
                    continue;
                }

                IabakoMailHelper mailHelper = new IabakoMailHelper(appConf.getNoReplyEmail(),
                        appConf.getEmailPersonalFrom(), user.getEmail(), messages.getLabel(user.getEnterprise().getLanguage(), "tracking_email_subject",
                        user.getFirstName(), GenericTools.formatDate(trackingList.get(0).getDate())), null);
                mailHelper.setTemplate(template);

                iabakoMailSender.sendMail(mailHelper);
            }
        }

        log.info("SendTrackingRecapControllerTimer ends successfully");
    }
}
